﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Threading.Tasks;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using Net.Chirash.Twitter.TweetZone.Properties;
using Net.Chirash.Twitter.TwitterClient;
using Net.Chirash.Twitter.TwitterDatabase;

namespace Net.Chirash.Twitter.TweetZone
{
    /// <summary>
    /// SettingsWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class SettingsWindow : Window
    {
        public SettingsWindow()
        {
            InitializeComponent();
        }

        #region PrivateFields

        private int refleshInterval = 60;
        private int numberOfStatusesToGet = 20;
        //TODO: Add DefaultValues

        #endregion

        #region Private Methods

        private void ChangeButtonState(bool isEnabled)
        {
            SaveButton.IsEnabled = isEnabled;
            CancelButton.IsEnabled = isEnabled;
            InitializeButton.IsEnabled = isEnabled;
            ResetButton.IsEnabled = isEnabled;
        }

        private void InitializeSettings()
        {
            //TODO: Initialize Operation
        }

        private void LoadSettings()
        {
            NumberOfStatusesToGetSlider.Value = Settings.Default.NumberOfStatusesToGet;

            int interval = (int)Settings.Default.RefreshInterval.TotalSeconds;
            switch (interval)
            {
                case 30:
                    Interval30SecondsRadioButton.IsChecked = true;
                    break;
                case 60:
                    Interval1minuteRadioButton.IsChecked = true;
                    break;
                case 180:
                    Interval3minutesRadioButton.IsChecked = true;
                    break;
                case 300:
                    Interval5minutesRadioButton.IsChecked = true;
                    break;
                case 600:
                    Interval10minutesRadioButton.IsChecked = true;
                    break;
                case 900:
                    Interval15minutesRadioButton.IsChecked = true;
                    break;
                default:
                    IntervalCustomRadioButton.IsChecked = true;
                    CustomIntervalTextBox.Text = interval.ToString();
                    break;
            }
        }

        private void SaveSettings()
        {
            Settings.Default.NumberOfStatusesToGet = (int)NumberOfStatusesToGetSlider.Value;

            if (Interval30SecondsRadioButton.IsChecked.Value)
            {
                Settings.Default.RefreshInterval = TimeSpan.FromSeconds(30);
            }
            else if (Interval1minuteRadioButton.IsChecked.Value)
            {
                Settings.Default.RefreshInterval = TimeSpan.FromSeconds(60);
            }
            else if (Interval3minutesRadioButton.IsChecked.Value)
            {
                Settings.Default.RefreshInterval = TimeSpan.FromSeconds(3 * 60);
            }
            else if (Interval5minutesRadioButton.IsChecked.Value)
            {
                Settings.Default.RefreshInterval = TimeSpan.FromSeconds(5 * 60);
            }
            else if (Interval10minutesRadioButton.IsChecked.Value)
            {
                Settings.Default.RefreshInterval = TimeSpan.FromSeconds(10 * 60);
            }
            else if (IntervalCustomRadioButton.IsChecked.Value)
            {
                Settings.Default.RefreshInterval = TimeSpan.FromSeconds(int.Parse(CustomIntervalTextBox.Text));
            }

            Settings.Default.Save();
            App.CurrentApp.TimerSynchronizer.Start((int)Settings.Default.RefreshInterval.TotalMilliseconds);
        }

        #endregion

        #region Events

        private void SaveButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //SaveProgressBar.Visibility = System.Windows.Visibility.Visible;
            ChangeButtonState(false);
            SaveSettings();
            //SaveProgressBar.Visibility = System.Windows.Visibility.Hidden;
            DialogResult = true;
        }

        private void CancelButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void ResetButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //TODO: Reset
        }

        private void InitializeButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string message = "あなたが変更した設定は全て失われ、最初の設定に戻ります。実行しますか";
            string caption = "TweetZoneの設定を初期化します";
            MessageBoxResult result = MessageBox.Show(message, caption, MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                //TODO: InitializeAsync
            }
        }

        private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            LoadSettings();
        }

        private void IntervalRadioButtonChecked(object sender, System.Windows.RoutedEventArgs e)
        {
        }

        private void test_receiveAllfromHomeTL_Click(object sender, RoutedEventArgs e)
        {
            const int total = 32000;
            const int step = 100;
            TaskScheduler uiThread = TaskScheduler.FromCurrentSynchronizationContext();
            long oldestUserID = long.MaxValue;

            var refreshTask = Task.Factory.StartNew(new Action(() =>
                {
                    var cmd = TwitterCommandFactory.CreateRemoteTwitterCommand();
                    var che = TwitterCommandFactory.CreateLocalTwitterCommand();
                    int counter = 0;
                    while (counter < total)
                    {
                        var option = new TimelineOption()
                        {
                            MaxID = oldestUserID,
                            Count = step,
                        };
                        Timeline tl = null;
                        try
                        {
                            tl = cmd.GetHomeTimeline(option);
                            che.UpdateStatuses(tl);
                        }
                        catch (Exception ex)
                        {
                            Task.Factory.StartNew(new Action(() => MessageBox.Show(ErrorMessageProvider.CreateErrorMessage(ex))));
                        }

                        if (tl != null && tl.Count() != 0)
                        {
                            if (oldestUserID == tl.Last().StatusID)
                            {
                                break; //打ち止め
                            }
                            else
                            {
                                oldestUserID = tl.Last().StatusID;
                                counter += tl.Count();
                            }
                        }

                        int sleepTime = 1;
                        for (int i = 1; i <= sleepTime; i++)
                        {
                            Task.Factory.StartNew(
                                new Action(() =>
                                    this.Title = string.Format("{0}/{1} Sleeping:{2}/{3}sec.", counter, total, i, sleepTime)
                                )
                                , CancellationToken.None, TaskCreationOptions.None, uiThread);
                            Thread.Sleep(1000);
                        }
                    }
                }))
                .ContinueWith(new Action<Task>((task) =>
                    {
                        this.Title = "completed";
                    }
                ), uiThread);

        }

        #endregion

    }
}
